<template>
  <div class="app-container">
    <el-card>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="封面图" prop="bannerPic">
          <oss :limit="1" v-model="form.bannerPic"></oss>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input maxlength="100" v-model="form.title" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <editor v-model="form.content" min-height="300px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { updateScientific } from "@/api/frist/scientific";
export default {
  name: "scientific",

  components: {
    oss: () => import("@/components/ImageUpload/oss.vue"),
  },

  created() {
    let data = sessionStorage.getItem("scientific");

    if (!data) {
      return;
    }

    this.form = JSON.parse(data);
  },

  data() {
    return {
      form: {
        bannerPic: "",
        title: "",
        enabled: 1,
        content: "",
      },
      rules: {
        bannerPic: [
          { required: true, message: "请输入封面图", trigger: "blur" },
        ],
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        enabled: [
          {
            required: true,
            message: "请输入0, 不启用; 1,启用",
            trigger: "blur",
          },
        ],
        content: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { validator: this.checkDescription, trigger: ['blur', 'change'] }

        ],
      },
    };
  },

  methods: {
    checkDescription(rule, value, callback) {
      const cleanedContent = value.replace(/<[^>]*>/g, '').trim();

      if (cleanedContent === '') {
        callback(new Error('内容不能为空'))
        console.log('Editor is empty');
      } else {
        callback()
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }

        if (this.form.id == null) {
          return;
        }
        updateScientific(this.form).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.$router.push({
            path: "/frist/scientific",
          });
        });
      });
    },

    cancel() {
      this.$router.push({
        path: "/frist/scientific",
      });
    }
  },
};
</script>

<style></style>
